<template>
  <a-spin :spinning="confirmLoading">
    <JFormContainer :disabled="disabled">
      <template #detail>
        <a-form ref="formRef" class="antd-modal-form" :labelCol="labelCol" :wrapperCol="wrapperCol" name="CInvoiceApplyAskForm">
          <a-row>

						<a-col :span="12">
							<a-form-item label="项目" v-bind="validateInfos.projectId" id="CInvoiceApplyAskForm-projectId" name="projectId">
								 <j-dict-select-tag showSearch="true"   v-model:value="formData.projectId"
                                   :disabled="disabledFlag"
                                   :trigger-change="true"
                                   @change="projectChange"
                                   dictCode="c_project_application,project_name,id"
                                   placeholder="请选择项目"  allow-clear />
							</a-form-item>
						</a-col>
						<a-col :span="12">
							<a-form-item label="子项目" v-bind="validateInfos.subProjectId" id="CInvoiceApplyAskForm-subProjectId" name="subProjectId">
								 <j-dict-select-tag showSearch="true"   v-model:value="formData.subProjectId"
                                   :disabled="disabledFlag"
                                   :trigger-change="true"
                                   @change="subProjectChange"
                                    :dictCode="subProjectDictCode"

                                   placeholder="请选择子项目"  allow-clear />
							</a-form-item>
						</a-col>
            <a-col :span="12">
              <a-form-item label="开票主体" v-bind="validateInfos.companyId" id="CInvoiceApplyAskForm-companyId" name="companyId">
                 <j-dict-select-tag showSearch="true"   v-model:value="formData.companyId"
                                   :disabled="disabledFlag"
                                   dictCode="c_company_info,company_name,id"
                                   placeholder="请选择开票主体--总包信息"
                                   :trigger-change="true"
                                   @change="companyChange"
                                   allow-clear />
              </a-form-item>
            </a-col>
            <a-col :span="12" v-if="formData.id ===''" >
              <a-form-item label="开票主体-开票信息" v-bind="validateInfos.invoiceId" id="CInvoiceApplyAskForm-invoiceId" name="invoiceId">
                 <j-dict-select-tag showSearch="true"   v-model:value="formData.invoiceId"
                                   :disabled="disabledFlag"
                                   :dictCode="invoiceDictCode"
                                   placeholder="请选择开票主体--总包信息--开票信息"
                                   :trigger-change="true"
                                   @change="invoiceChange"
                                   allow-clear />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="收票主体" v-bind="validateInfos.contractingId" id="CInvoiceApplyAskForm-contractingId" name="contractingId">
                 <j-dict-select-tag showSearch="true"   v-model:value="formData.contractingId"
                                   :disabled="disabledFlag"
                                   :trigger-change="true"
                                   @change="buyCompanyChange"
                                   dictCode="c_contracting_unit,name,id"
                                   placeholder="请选择收票主体--发包商"  allow-clear />
              </a-form-item>
            </a-col>
            <a-col :span="12" v-if="formData.id ===''" >
              <a-form-item label="收票主体-开票信息" v-bind="validateInfos.buyInvoiceId" id="CInvoiceApplyAskForm-BuyInvoiceId" name="BuyInvoiceId">
                 <j-dict-select-tag showSearch="true"   v-model:value="formData.buyInvoiceId"
                                   :disabled="disabledFlag"
                                   :dictCode="buyInvoiceDictCode"
                                   placeholder="请选择收票主体--发包商--开票信息"
                                   :trigger-change="true"
                                   @change="buyInvoiceChange"
                                   allow-clear />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="申请标题" v-bind="validateInfos.title" id="CInvoiceApplyAskForm-title" name="title">
                <a-input v-model:value="formData.title" :disabled="disabledFlag" placeholder="请输入申请标题"  allow-clear ></a-input>
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="附件" v-bind="validateInfos.appendix" id="CInvoiceApplyAskForm-appendix" name="appendix">
                <j-upload v-model:value="formData.appendix"  dragger="true"   :show-upload-list="{ showDownloadIcon: true, showRemoveIcon: true }" ></j-upload>
              </a-form-item>
            </a-col>




            <a-divider >发票信息</a-divider >

						<a-col :span="12">
							<a-form-item label="项目名称" v-bind="validateInfos.projectName" id="CInvoiceApplyAskForm-projectName" name="projectName">
								<a-input v-model:value="formData.projectName" :disabled="disabledFlag" placeholder="请输入项目名称"  allow-clear ></a-input>
							</a-form-item>
						</a-col>
            <a-col :span="12">
              <a-form-item label="发票类型" v-bind="validateInfos.invoiceType" id="CInvoiceApplyAskForm-invoiceType" name="invoiceType">
                 <j-dict-select-tag showSearch="true"   v-model:value="formData.invoiceType" :disabled="disabledFlag" dictCode="InvoiceType" placeholder="请选择发票类型"  allow-clear />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="金额" v-bind="validateInfos.amount" id="CInvoiceApplyAskForm-amount" name="amount">
                <a-input-number v-model:value="formData.amount" :disabled="disabledFlag" placeholder="请输入金额" style="width: 100%" />
              </a-form-item>
            </a-col>
						<a-col :span="12">
							<a-form-item label="税率%" v-bind="validateInfos.taxRate" id="CInvoiceApplyAskForm-taxRate" name="taxRate">
								<a-input-number v-model:value="formData.taxRate" :disabled="disabledFlag" placeholder="请输入税率" style="width: 100%" />
							</a-form-item>
						</a-col>
            <a-col :span="12">
              <a-form-item label="税额" v-bind="validateInfos.taxAmount" id="CInvoiceApplyAskForm-taxAmount" name="taxAmount">
                <a-input-number v-model:value="formData.taxAmount" :disabled="disabledFlag" placeholder="请输入税额" style="width: 100%" />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="建筑服务发生地" v-bind="validateInfos.buildingAdd" id="CInvoiceApplyAskForm-buildingAdd" name="buildingAdd">
                <a-input v-model:value="formData.buildingAdd" placeholder="请输入建筑服务发生地"  allow-clear ></a-input>
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="建筑项目名称" v-bind="validateInfos.buildingName" id="CInvoiceApplyAskForm-buildingName" name="buildingName">
                <a-input v-model:value="formData.buildingName" :disabled="disabledFlag" placeholder="请输入建筑项目名称"  allow-clear ></a-input>
              </a-form-item>
            </a-col>
						<a-col :span="12">
							<a-form-item label="发票的备注信息" v-bind="validateInfos.remarks" id="CInvoiceApplyAskForm-remarks" name="remarks">
								<a-input v-model:value="formData.remarks" :disabled="disabledFlag" placeholder="请输入发票的备注信息"  allow-clear ></a-input>
							</a-form-item>
						</a-col>

            <a-divider >帐户信息</a-divider >
						<a-col :span="12">
							<a-form-item label="销售方名称" v-bind="validateInfos.sellerName" id="CInvoiceApplyAskForm-sellerName" name="sellerName">
								<a-input v-model:value="formData.sellerName":disabled="disabledFlag" placeholder="请输入销售方名称"  allow-clear ></a-input>
							</a-form-item>
						</a-col>
						<a-col :span="12">
							<a-form-item label="销售方的统一社会信用代码或纳税人识别号" v-bind="validateInfos.sellerTaxId" id="CInvoiceApplyAskForm-sellerTaxId" name="sellerTaxId">
								<a-input v-model:value="formData.sellerTaxId" :disabled="disabledFlag" placeholder="请输入销售方的统一社会信用代码或纳税人识别号"  allow-clear ></a-input>
							</a-form-item>
						</a-col>
						<a-col :span="12">
							<a-form-item label="购买方名称" v-bind="validateInfos.buyerName" id="CInvoiceApplyAskForm-buyerName" name="buyerName">
								<a-input v-model:value="formData.buyerName":disabled="disabledFlag"  placeholder="请输入购买方名称"  allow-clear ></a-input>
							</a-form-item>
						</a-col>
						<a-col :span="12">
							<a-form-item label="购买方的统一社会信用代码或纳税人识别号" v-bind="validateInfos.buyerTaxId" id="CInvoiceApplyAskForm-buyerTaxId" name="buyerTaxId">
								<a-input v-model:value="formData.buyerTaxId" :disabled="disabledFlag" placeholder="请输入购买方的统一社会信用代码或纳税人识别号"  allow-clear ></a-input>
							</a-form-item>
						</a-col>
            </a-row>


            <a-row v-if="disabledFlag===true">
              <a-divider >审核</a-divider >
              <a-col :span="24" v-if="formData.id">
                <a-form-item label="审核" v-bind="validateInfos.status" id="CPaymentRequestApplyForm-status" name="status">
                  <j-dict-select-tag type='radio' v-model:value="formData.status" dictCode="Audit" placeholder="请选择"  allow-clear />
                </a-form-item>
              </a-col>


              <a-col :span="24"   v-if="formData.id" >
                <a-form-item label="审核描述" v-bind="validateInfos.reviewDescription" id="CInvoiceApplyAskForm-reviewDescription" name="reviewDescription">
                  <a-textarea v-model:value="formData.reviewDescription" :rows="4" placeholder="请输入审核描述" />
                </a-form-item>
              </a-col>


              <a-col :span="12"  v-if="formData.status ==='已开票' || formData.status ==='待开票' || formData.status ==='已开票' ">
                <a-form-item label="财务人" v-bind="validateInfos.financialUserId" id="CInvoiceApplyAskForm-financialUserId" name="financialUserId">
                   <j-dict-select-tag showSearch="true"   v-model:value="formData.financialUserId" dictCode="sys_user,username,id" placeholder="请选择财务人"  allow-clear />
                </a-form-item>
              </a-col>
              <a-col :span="12" v-if="formData.status ==='已开票' || formData.status ==='待开票'  ">
                <a-form-item label="财务审核时间" v-bind="validateInfos.financialTime" id="CInvoiceApplyAskForm-financialTime" name="financialTime">
                  <a-date-picker placeholder="请选择财务审核时间"  v-model:value="formData.financialTime" showTime value-format="YYYY-MM-DD HH:mm:ss" style="width: 100%"  allow-clear />
                </a-form-item>
              </a-col>
              <a-col :span="12" v-if="formData.status ==='已开票' || formData.status ==='待开票'   ">
                <a-form-item label="开票记录" v-bind="validateInfos.financialTime" id="CInvoiceApplyAskForm-financialTime" name="financialTime">
                  <a-date-picker placeholder="请选择财务审核时间"  v-model:value="formData.financialTime" showTime value-format="YYYY-MM-DD HH:mm:ss" style="width: 100%"  allow-clear />
                </a-form-item>
              </a-col>

              <a-col :span="24"  v-if="formData.status ==='已开票' || formData.status ==='待开票'   ">
                <a-form-item label="开票记录" v-bind="validateInfos.applyId" id="CSubProjectForm-applyId" name="applyId">
                   <j-dict-select-tag showSearch="true"    v-model:value="formData.applyId"
                                      dictCode="c_invoice_apply,project_name,id"
                                      placeholder="请输入发票"  allow-clear />
                </a-form-item>
              </a-col>




          </a-row>
        </a-form>
      </template>
    </JFormContainer>
  </a-spin>
</template>

<script lang="ts" setup>
  import { ref, reactive, defineExpose, nextTick, defineProps, computed, onMounted } from 'vue';
  import { defHttp } from '/@/utils/http/axios';
  import { useMessage } from '/@/hooks/web/useMessage';
  import JDictSelectTag from '/@/components/Form/src/jeecg/components/JDictSelectTag.vue';
  import { getValueType } from '/@/utils';
  import { invoiceInfoById, saveOrUpdate, applicationInfoById, cSubProjectById } from '../CInvoiceApplyAsk.api';
  import { Form } from 'ant-design-vue';
  import JUpload from '/@/components/Form/src/jeecg/components/JUpload/JUpload.vue';
  import JFormContainer from '/@/components/Form/src/container/JFormContainer.vue';
  import { getBankById } from '@/views/paymentrequestapply/CPaymentRequestApply.api';

  const props = defineProps({
    formDisabled: { type: Boolean, default: false },
    formData: { type: Object, default: () => ({})},
    formBpm: { type: Boolean, default: true }
  });
  const formRef = ref();
  const disabledFlag = ref(false)
  const invoiceDictCode = ref("c_invoice_info,companyname,id,relevance_id=0");
  const buyInvoiceDictCode = ref("c_invoice_info,companyname,id,relevance_id=0");
  const subProjectDictCode = ref("c_sub_project,sub_project_name,id,project_id=123");


  const useForm = Form.useForm;
  const emit = defineEmits(['register', 'ok']);
  const formData = reactive<Record<string, any>>({
    id: '',
    status: '',   
    projectId: '',   
    subProjectId: '',   
    projectName: '',   
    taxAmount: undefined,
    invoicer: '',   
    taxRate: 9,
    amount: undefined,
    invoiceType: '专票',
    remarks: '',   
    sellerName: '',   
    sellerTaxId: '',   
    buyerName: '',   
    buyerTaxId: '',   
    reviewerUserId: '',   
    reviewTime: '',   
    reviewDescription: '',   
    submitterUserId: '',   
    submissionTime: '',   
    financialUserId: '',   
    financialTime: '',   
    applyId: '',   
    buildingAdd: '',   
    buildingName: '',   
    companyId: '',   
    contractingId: '',
    invoiceId:'',
    title:'',
    appendix:''
  });
  const { createMessage } = useMessage();
  const labelCol = ref<any>({ xs: { span: 24 }, sm: { span: 5 } });
  const wrapperCol = ref<any>({ xs: { span: 24 }, sm: { span: 16 } });
  const confirmLoading = ref<boolean>(false);
  //表单验证
  const validatorRules = reactive({
    projectId: [{ required: true, message: '请输入项目ID!'},],
    title: [{ required: true, message: '请输入申请标题!'},],
  });
  const { resetFields, validate, validateInfos } = useForm(formData, validatorRules, { immediate: false });

  // 表单禁用
  const disabled = computed(()=>{
    if(props.formBpm === true){
      if(props.formData.disabled === false){
        return false;
      }else{
        return true;
      }
    }
    return props.formDisabled;
  });

  
  /**
   * 新增
   */
  function add() {
    edit({},"新增");
  }

  /**
   * 编辑
   */
  function edit(record,btn) {
    nextTick(() => {
      resetFields();
      const tmpData = {};
      Object.keys(formData).forEach((key) => {
        if(record.hasOwnProperty(key)){
          tmpData[key] = record[key]
        }
        if(key ==="status"){
          if(record[key] ==="待开票"){
            tmpData[key] = "同意"
          }
        }
      })
      //赋值
      Object.assign(formData, tmpData);
    });

    disabledFlag.value == false

    if(btn ==='编辑' || btn ==='新增' ){
      disabledFlag.value = false
    }else {
      disabledFlag.value = true
    }
  }

  /**
   * 提交数据
   */
  async function submitForm() {
    try {
      // 触发表单验证
      await validate();
    } catch ({ errorFields }) {
      if (errorFields) {
        const firstField = errorFields[0];
        if (firstField) {
          formRef.value.scrollToField(firstField.name, { behavior: 'smooth', block: 'center' });
        }
      }
      return Promise.reject(errorFields);
    }
    confirmLoading.value = true;
    const isUpdate = ref<boolean>(false);
    //时间格式化
    let model = formData;
    if (model.id) {
      isUpdate.value = true;
    }
    //循环数据
    for (let data in model) {
      //如果该数据是数组并且是字符串类型
      if (model[data] instanceof Array) {
        let valueType = getValueType(formRef.value.getProps, data);
        //如果是字符串类型的需要变成以逗号分割的字符串
        if (valueType === 'string') {
          model[data] = model[data].join(',');
        }
      }
    }
    await saveOrUpdate(model, isUpdate.value)
      .then((res) => {
        if (res.success) {
          createMessage.success(res.message);
          emit('ok');
        } else {
          createMessage.warning(res.message);
        }
      })
      .finally(() => {
        confirmLoading.value = false;
      });
  }

  async function companyChange(value){

    if(value){
      formData.invoiceId = "";
      invoiceDictCode.value = "c_invoice_info,companyname,id,relevance_id="+value
      formData.sellerName = "";
      formData.sellerTaxId = "";
    }
    //查询信息
  }
  async function buyCompanyChange(value){
    if(value){
      formData.buyInvoiceId = "";
      buyInvoiceDictCode.value = "c_invoice_info,companyname,id,relevance_id="+value
      formData.buyerName = "";
      formData.buyerTaxId = "";
    }
    //查询信息
  }

  async function invoiceChange(value){
    if(value){
      const param = {'id':value}
      try {
        const result = await invoiceInfoById(param)
        if(result){
          formData.sellerName =result.companyname;
          formData.sellerTaxId = result.taxcode;
        }
      }catch (e) {

      }
    }else {
      formData.sellerName = "";
      formData.sellerTaxId = "";
    }
  }
  async function buyInvoiceChange(value){
    if(value){
      const param = {'id':value}
      try {
        const result = await invoiceInfoById(param)
        if(result){
          formData.buyerName =result.companyname;
          formData.buyerTaxId = result.taxcode;
        }
      }catch (e) {

      }
    }else {
      formData.buyerName = "";
      formData.buyerTaxId = "";
    }
  }

  async function subProjectChange(value){
    if(value){
      const param = {'id':value}
      try {
        const result = await cSubProjectById(param)
        if(result){
          formData.buildingName =result.subProjectName;
          formData.buildingAdd =result.address;
        }
      }catch (e) {

      }
    }else {
      formData.buildingName = "";
      formData.buildingAdd ="";

    }
  }

  async function projectChange(value){
    if(value){
      subProjectDictCode.value = "c_sub_project,sub_project_name,id,project_id="+value
      const param = {'id':value}
      try {
        const result = await applicationInfoById(param)
        if(result){
          formData.projectName =result.projectName;
          formData.address = result.address;
          formData.contractingId = result.contractingUnit;//发包商
          formData.companyId = result.companyInfoId
        }
      }catch (e) {

      }
    }else {
      formData.projectName = "";
      formData.address = "";
      formData.contractingId = "";
      formData.companyId = "";
      subProjectDictCode.value = "c_sub_project,sub_project_name,id,project_id=123"
    }
    companyChange(formData.companyId)
    buyCompanyChange(formData.contractingId)
   // invoiceChange()

  }





  defineExpose({
    add,
    edit,
    submitForm,
    invoiceDictCode,
    buyInvoiceDictCode,
    buyCompanyChange,
  });
</script>

<style lang="less" scoped>
  .antd-modal-form {
    padding: 14px;
  }
</style>
